package gitee.com.paopaoyu.helloworldclient;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class DaprHelloworldClientApplication {

	private final static String bodyTmpl="{\"data\": {\"orderId\": \"%s\"}}";

    public static void main(String[] args) throws IOException, InterruptedException {


		Thread sendThread = new Thread(new Runnable() {
			public void run() {
				int i=0;
				while(!Thread.interrupted()){
					try {
						Thread.sleep(5000);
						i++;
						String body=String.format(bodyTmpl,String.valueOf(i));
						sendRequest(body);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});

		sendThread.start();
		Thread.sleep(5*60*60*1000);

    }




	public static void sendRequest(String body) throws IOException {

	String httpPort = System.getenv("DAPR_HTTP_PORT");
	if (httpPort == null) {
		httpPort = "3500";
	}

	String resultUrl = "http://localhost:" + httpPort + "/v1.0/invoke/goapp/method/neworder";

	URL url = new URL(resultUrl);

	HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	connection.setRequestMethod("POST");
	connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
	connection.setRequestProperty("Connection", "Keep-Alive");
	connection.setUseCaches(false);
	connection.setDoOutput(true);
	connection.setDoInput(true);
	System.out.println("request body:"+body);
	DataOutputStream out = new DataOutputStream(connection.getOutputStream());
	out.write(body.getBytes("UTF-8"));
	out.flush();
	out.close();


	connection.connect();

	BufferedReader bReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

	String line, resultStr = "";

	while (null != (line = bReader.readLine())) {
		resultStr += line;
	}
	System.out.println(resultStr);
	bReader.close();

}

}



